package com.ysy.logistics.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ysy.logistics.entities.system.Meta;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;

/**
 * @ClassDescription:
 * @Author:姚斯羽
 * @Create:2025/3/16 3:33
 **/
@Slf4j
public class MetaTypeHandler extends BaseTypeHandler<Meta> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Meta parameter, JdbcType jdbcType) throws SQLException {
        ObjectMapper om = new ObjectMapper();
        String json = null;
        try {
            json = om.writeValueAsString(parameter);
            if ((Objects.nonNull(json))){
                ps.setString(i, json);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public Meta getNullableResult(ResultSet rs, String columnName) throws SQLException {
        ObjectMapper om = new ObjectMapper();
        String json = rs.getString(columnName);
        Meta meta = null;
        try {
            if ((Objects.nonNull(json))){
                meta = om.readValue(json, Meta.class);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return meta;
    }

    @Override
    public Meta getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return null;
    }

    @Override
    public Meta getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return null;
    }
}
